#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: bao
# @Date:   2017-01-16 11:59:29
# @Last Modified by:   bao
# @Last Modified time: 2017-07-26 16:40:22

from Unit import *
from Flow import *


class Scheduler:
    """ Scheduler maintains flow information"""

    def __init__(self):
        self.flows = []  # Initial flows

        self.runningFlows = []  # Running flows

        self.finishedFlows = []  # Finished flows

        self.Links = {}

        self.H2SLinks = {}

        self.trafficType = ""

        self.fileName = ""

    def AssignLinks(self, links):
        """
        We need links information because we need to update flow info
        """
        self.Links = links

    def AssignFlows(self, args):
        """
        Read flow traces
        """
        self.trafficType = args[0]
        self.fileName = args[1]
        f = open(inDir + self.fileName, "r")
        for line in f.readlines():
            l = line.split()
            flow = Flow()
            if self.trafficType == 'CDF':
                flow.startId = int(l[1])
                flow.endId = int(l[2])
                flow.SetFlowSize(float(l[4]) * 8)
                flow.startTime = float(l[0])
                flow.flowId = len(self.flows) + 1
            else:  # static
                flow.startId = int(l[0])
                flow.endId = int(l[1])
                flow.flowId = len(self.flows) + 1
            self.flows.append(flow)
        f.close()

    def GetAllFlows(self):
        return self.flows

    def UpdateFlow(self, curFlow, eventType, eventQueue, curTime):
        pass

    def PrintFlows(self):
        """
        print finishedFlows
        
        flow completion time(FCT)
        Average FCTs
        99th %-tile FCTs

        (0,100KB]: Avg 
        (0,100KB]: 99th Percentile 
        (100KB,10MB]: Avg
        (10MB,++): Avg
        """

        f_name = outDir + self.fileName
        f = open(f_name, "w")
        if self.trafficType == 'CDF':

            overall_fct = 0.0
            for flow in self.finishedFlows:

                flowTransTime = flow.finishTime - flow.startTime
                overall_fct += flowTransTime
                if flowTransTime != 0:
                    flow.bw = flow.flowSize / flowTransTime
                    print >> f, "flowId: %d flowSize: %d fct: %f\t%f\t%f bw %f\t energy: %s" % (
                        flow.flowId, flow.flowSize, flowTransTime, flow.startTime, flow.finishTime, flow.bw, flow.energy)

            overall_avg_fct = overall_fct / len(self.flows)
            print >> f, overall_fct, overall_avg_fct

        else:
            for flow in self.flows:
                print >> f, flow.bw
        f.close()
